#!/usr/bin/python

import os
import sys
import datetime
import urllib
import re
import commands
from optparse import OptionParser

from movie.vote.models import Movie

MOVIE_SEARCH_BIN = './movie-search'

def GetRottenReviewUrl(name):
  url = commands.getoutput('%s --rotten-review "%s"' % (MOVIE_SEARCH_BIN, name))
  if url and url != 'nil':
    return url
  return None

def GetMetacriticReviewUrl(name):
  url = commands.getoutput('%s --metacritic-review "%s"' % (MOVIE_SEARCH_BIN, name))
  if url and url != 'nil':
    return url
  return None

def UpdateMovieReviews(days_back, search_web):
  if not days_back:
    movies = Movie.objects.all()
  else:
    cutoff = datetime.datetime.now() - datetime.timedelta(days_back)
    movies = Movie.objects.filter(date_added__gt=cutoff)
  for movie in movies:
    if not movie.imdb_url or (movie.metacritic_url and movie.rotten_url):
      continue

    if not movie.metacritic_url:
      metacritic_url = GetMetacriticReviewUrl(movie.name)
      if metacritic_url:
        movie.metacritic_url = metacritic_url
        movie.save()
        print '%s %s' % (movie, movie.metacritic_url)

    if not movie.rotten_url:
      rotten_url = GetRottenReviewUrl(movie.name)
      if rotten_url:
        movie.rotten_url = rotten_url
        movie.save()
        print '%s %s' % (movie, movie.rotten_url)


if __name__ == '__main__':
  usage = "usage: %prog [options]"
  parser = OptionParser(usage)
  parser.add_option('-d', '--days_back', type='int', dest='days_back', default=5,
                    help='skip movies older than this many days')
  parser.add_option('-s', '--search_web', action='store_true', default=False,
                    dest='search_web', help='search web for reviews')
  (options, args) = parser.parse_args()
  UpdateMovieReviews(days_back=options.days_back, search_web=options.search_web)
